<?php
// +----------------------------------------------------------------------
// | 店铺运费
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Model;
use think\Validate;

class ShopFreight extends Model
{
	protected $name = 'freight';
	
	//地区，一对多关联
	public function freightCostList(){
		return $this->hasMany('ShopFreightValue','freight_id');
    }
	
	/**
     * 获取模板列表
     * @param type $shopId
     * @return type
     */
	public function getList($shopId)
    {
    	$model = new self;
		$model = $model->where("shop_id",$shopId);
		$model = $model->where("is_del",0);
		$model = $model->field("is_del,add_time",true);
		$model = $model->order("add_time","desc");
		return $model->all(null,'freightList');
    }
	
	/**
     * 获取购物车运费
     * @param type $shopId
     * @return type
     */
	public function getCartPostage($cartInfo,$province)
    {
    	$value = 0;
    	$totalPrice = self::getSumPrice($cartInfo, 'sale_price');
    	
    	//根据购物车信息- 获取freight_id分组信息
    	$freights = [];
    	$freightIds =  array_unique(array_column($cartInfo, 'freight_id'));
    	foreach($freightIds as $k=> $freight_id){
    		$arr = [ 'freight_id'=>$freight_id, 'cart_num'=>0,'shop_id'=>$cartInfo[0]['shop_id'] ];
    		foreach($cartInfo as $key => $val){
	    		if($freight_id == $val['freight_id']){
	    			$arr['cart_num'] = ( $arr['cart_num'] +$val['cart_num']);
	    		}
	    	}
	    	$freights[] = $arr;
    	}
    	
    	
    	//计算
    	foreach( $freights as $k=> $val ){
    		
    		//获取模板, 模板不存在则跳过当前循环
    		if( !$freight  = self::get($val['freight_id']) ){
    			if(!$freight = self::where("shop_id",$val['shop_id'])->where("is_default",1)->find()){
    				continue;
    			}
    		}
    		

    		// 已达到满额包邮条件则跳过当前循环
    		if( $freight ->is_free_shipping == 1 && $totalPrice >= $freight->full_isfree ){
    			continue;
    		}

    		// 获取地区运费, 地区不存在则跳过当前循环
    		if(!$cost = $freight->freightCostList()->where('province',$province)->find()){
	    		if(!$cost = $freight->freightCostList()->where('province','全国')->find()){
	    			continue;
	    		}
    		}
    		
    		//获得同模板下的所有商品运费
    		if($cost['continued_num']<1)  $cost['continued_num'] = 1;
    		$renewNum = ceil( ($val['cart_num'] - $cost['first_num'])  / $cost['continued_num']);
    		$value = $value + $cost['freight'] + ($renewNum * $cost['renew']);
    		
    	}
		return $value ? round($value,2) : 0;
    }
    
    
    /**获取某个字段总金额
     * @param $cartInfo
     * @param $key 键名
     * @return int|string
     */
    public static function getSumPrice($cartInfo, $key = 'price',$num=2)
    {
        $SumPrice = 0;
        foreach ($cartInfo as $cart) {
            $SumPrice = bcadd($SumPrice, bcmul($cart['cart_num'], $cart[$key], 2), $num);
        }
        return $SumPrice;
    }
    
}
